public class Rational extends Object{
    int numerator = 1 ;   //分子
    int denominator = 1; //分母
    Rational(){}
    Rational(int a,int b){
        if(b!=1){
            int c = f(Math.abs(a), b);  //计算最大公约数
            numerator = a / c;
            denominator = b / c;
        }
        else {
            numerator = a;
            denominator = b;
        }
        if(numerator<0&&denominator<0) {
            numerator = -numerator;
            denominator = -denominator;
        }
        else if(denominator<0){
            numerator = -numerator;
            denominator = -denominator;
        }
    }
    void setNumerator(int a) {  //设置分子
        if (denominator != 1) {
            int c = f(Math.abs(a), denominator);  //计算最大公约数
            numerator = a / c;
            denominator = denominator / c;
        }
        else {
            numerator = a;
        }
        if(numerator<0&&denominator<0) {
            numerator = -numerator;
            denominator = -denominator;
        }
    }
    void setDenominator(int b) {  //设置分母
        if (b != 1) {
            int c = f(numerator, Math.abs(b));  //计算最大公约数
            numerator = numerator / c;
            denominator = b / c;
        }
        else {
            denominator = b;
        }
        if(numerator<0&&denominator<0) {
            numerator = -numerator;
            denominator = -denominator;
        }
    }
    int getNumerator() {
        return numerator;
    }
    int getDenominator() {
        return denominator;
    }
    int f(int a,int b) { //求a和b的最大公约数
        if(a==0) {
            return 1;
        }
        if(a<b) {
            int c=a;
            a=b;
            b=c;
        }
        int r=a%b;
        while(r!=0) {
            a=b;
            b=r;
            r=a%b;
        }
        return b;
    }
    @Override
    public String toString(){
        StringBuffer Bf = new StringBuffer();
        if (this.denominator == 0){
            return "wrong";
        }
        if (this.numerator % this.denominator == 0){
            Bf.append(this.numerator/this.denominator);
        }
        else {
            Bf.append(this.numerator);
            Bf.append('/');
            Bf.append(this.denominator);
        }
        String s = new String(Bf);
        return s;
    }
}
